package com.kafka.demo.consumer.offset;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
public class KafkaConsumerOffset {

    public static final String brokerList = "localhost:9090";
    public static final String topic = "my-replicated-topic";
    public static final String groupId = "group.demo";
    public static final AtomicBoolean isRunning = new AtomicBoolean(true);

    public static Properties initConfig() {
        Properties properties = new Properties();
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, brokerList);
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);
        properties.put(ConsumerConfig.CLIENT_ID_CONFIG, "consumer.client.id.demo");
        return properties;
    }

    public static void main(String[] args) {
        Properties properties = initConfig();
        KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties);

        TopicPartition tp = new TopicPartition(topic, 0);
        consumer.assign(Arrays.asList(tp));

        try {
            long lastedConsumedOffset = -1;
            while (true) {
                ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1000));
                if (records.isEmpty()) {
                    break;
                }
                List<ConsumerRecord<String, String>> partitionRecords = records.records(tp);
                lastedConsumedOffset = partitionRecords.get(partitionRecords.size() - 1).offset();
                // 对整个消息集（poll 到的 record）做同步提交
                consumer.commitSync();
            }
            System.out.println("consumed offset is : " + lastedConsumedOffset);

            OffsetAndMetadata offsetAndMetadata = consumer.committed(tp);
            System.out.println("committed offset is : " + offsetAndMetadata.offset()
                    + ", metadata : " + offsetAndMetadata.metadata());

            long position = consumer.position(tp);
            System.out.println("the offset of next record is : " + position);
        } catch (Exception e) {
            log.error("occur exception : " + e);
        } finally {
            consumer.close();
        }

    }

}
